'use client'

import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import VerseCard from '../components/VerseCard'
import DrawCardButton from '../components/DrawCardButton'
import ParticleEffect from '../components/ParticleEffect'
import versesDataRaw from '../data/verses.json'
import { Download, Github, Heart } from 'lucide-react'
import html2canvas from 'html2canvas'

// 类型安全的数据访问
const versesData = versesDataRaw as { verses: Verse[] }

interface Verse {
  id: number
  book: string
  chapter: number
  verse: number
  content: string
  translation: string
  keywords: string[]
  background: string | string[]
  mood: string
}

export default function Home() {
  const [currentVerse, setCurrentVerse] = useState<Verse | null>(null)
  const [isDrawing, setIsDrawing] = useState(false)
  const [showParticles, setShowParticles] = useState(false)
  const [savedVerses, setSavedVerses] = useState<number[]>([])
  const [verses, setVerses] = useState<Verse[]>([])

  // 初始化时显示随机经文
  useEffect(() => {
    setVerses(versesData.verses)
    // 每次刷新都显示不同的随机经文
    const randomIndex = Math.floor(Math.random() * versesData.verses.length)
    const randomVerse = versesData.verses[randomIndex]
    setCurrentVerse(randomVerse)
  }, [])

  // 从本地存储加载收藏的经文
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('savedVerses')
      if (saved) {
        setSavedVerses(JSON.parse(saved))
      }
    }
  }, [])

  const drawNewCard = async () => {
    if (verses.length === 0) return
    
    setIsDrawing(true)
    setShowParticles(true)
    
    // 模拟抽卡延迟
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 随机选择一张新卡片
    const randomIndex = Math.floor(Math.random() * verses.length)
    const newVerse = verses[randomIndex]
    setCurrentVerse(newVerse)
    
    setIsDrawing(false)
    
    // 粒子效果持续一段时间后消失
    setTimeout(() => setShowParticles(false), 3000)
  }

  const saveVerse = () => {
    if (!currentVerse) return
    
    const newSavedVerses = [...savedVerses, currentVerse.id]
    setSavedVerses(newSavedVerses)
    
    if (typeof window !== 'undefined') {
      localStorage.setItem('savedVerses', JSON.stringify(newSavedVerses))
    }
    
    // 显示保存成功的反馈
    alert('经文已保存到收藏夹！')
  }

  const shareVerse = async () => {
    if (!currentVerse) return

    const shareText = `"${currentVerse.content}" - ${currentVerse.book} ${currentVerse.chapter}:${currentVerse.verse}`
    
    if (navigator.share) {
      try {
        await navigator.share({
          title: '每日经文卡',
          text: shareText,
          url: window.location.href,
        })
      } catch (error) {
        console.log('分享取消或失败')
      }
    } else {
      // 降级到复制到剪贴板
      try {
        await navigator.clipboard.writeText(shareText)
        alert('经文已复制到剪贴板！')
      } catch (error) {
        console.log('复制失败')
      }
    }
  }

  const downloadCard = async () => {
    if (!currentVerse) {
      alert('请先生成卡片')
      return
    }
    const el = document.getElementById('verse-card') as HTMLElement | null
    if (!el) {
      alert('没有找到卡片区域')
      return
    }
    // 隐藏卡片内的操作按钮，避免截入
    const tools = el.querySelector('.action-buttons') as HTMLElement | null
    if (tools) tools.style.opacity = '0'
    try {
      const canvas = await html2canvas(el, {
        useCORS: true,
        allowTaint: false,
        backgroundColor: null,
        scale: 2,
        logging: false,
        ignoreElements: (node) =>
          node instanceof HTMLElement &&
          (node.classList.contains('action-buttons') || (node as HTMLElement).dataset.ignore === 'true'),
      })
      if (tools) tools.style.opacity = ''
      const link = document.createElement('a')
      const name = `${currentVerse.book}${currentVerse.chapter}_${currentVerse.verse}`
      link.download = `经文卡片-${name}.png`
      link.href = canvas.toDataURL('image/png')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } catch (e) {
      if (tools) tools.style.opacity = ''
      console.error('下载失败:', e)
      alert('下载失败，请稍后重试')
    }
  }

  return (
    <main className="min-h-screen relative overflow-hidden">
      {/* 粒子效果 */}
      <ParticleEffect isActive={showParticles} />
      
      {/* 背景装饰 */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute -top-40 -right-40 w-80 h-80 bg-purple-300 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-float"></div>
        <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-blue-300 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-float" style={{ animationDelay: '2s' }}></div>
        <div className="absolute top-40 left-1/2 w-80 h-80 bg-pink-300 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-float" style={{ animationDelay: '4s' }}></div>
      </div>

      {/* 主要内容 */}
      <div className="relative z-20 container mx-auto px-4 py-8">
        {/* 头部 */}
        <motion.header 
          className="text-center mb-12"
          initial={{ y: -50, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ duration: 0.8 }}
        >
          <div className="flex items-center justify-center gap-4 mb-4">
            <img 
              src="/logo.svg" 
              alt="圣经图标" 
              className="w-12 h-12 md:w-16 md:h-16 text-blue-600"
              style={{ filter: 'hue-rotate(220deg) saturate(1.2)' }}
            />
            <h1 className="text-4xl md:text-6xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
              每日经文卡
            </h1>
          </div>
          <p className="text-gray-600 text-lg md:text-xl max-w-2xl mx-auto">
            每天获取一张精美的圣经经文卡片，让神的话语照亮你的心灵
          </p>
        </motion.header>

        {/* 卡片展示区域 */}
        <div className="flex flex-col items-center gap-8 mb-12">
          <AnimatePresence mode="wait">
            {currentVerse && (
              <VerseCard
                key={currentVerse.id}
                verse={currentVerse}
                isFlipping={isDrawing}
                onSave={saveVerse}
                onShare={shareVerse}
                onDownload={downloadCard}
              />
            )}
          </AnimatePresence>

          {/* 抽卡按钮 */}
          <DrawCardButton
            onClick={drawNewCard}
            isDrawing={isDrawing}
          />
        </div>

        {/* 功能按钮区域 */}
        <motion.div 
          className="flex justify-center gap-4 mb-12"
          initial={{ y: 50, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ delay: 1, duration: 0.8 }}
        >
          <button
            onClick={downloadCard}
            className="flex items-center gap-2 px-6 py-3 bg-white/80 backdrop-blur-sm rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105"
          >
            <Download className="w-5 h-5 text-gray-700" />
            <span className="text-gray-700 font-medium">下载卡片</span>
          </button>
          
          <button
            onClick={() => window.open('https://gitee.com/yuhal/card', '_blank')}
            className="flex items-center gap-2 px-6 py-3 bg-white/80 backdrop-blur-sm rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105"
          >
            <Github className="w-5 h-5 text-gray-700" />
            <span className="text-gray-700 font-medium">源码</span>
          </button>
        </motion.div>

        {/* 统计信息 */}
        <motion.div 
          className="text-center text-gray-500"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 1.5, duration: 0.8 }}
        >
          <p className="mt-2 text-sm">
            经文库共收录 {verses.length} 段精选经文
          </p>
        </motion.div>
      </div>

      {/* 底部装饰 */}
      <div className="absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-white/50 to-transparent pointer-events-none"></div>
    </main>
  )
}